﻿using BCCommon;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepSpecificFormItem;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.WorkflowActivity.WorkflowActivityStepSpecificFormItem
{
    /// <summary>
    /// 工作流活动特殊表单项
    /// </summary>
	public class WorkflowActivityStepSpecificFormItemData : IWorkflowActivityStepSpecificFormItemData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM oa_workflowactivitystepspecificformitem";
        private const string QUERY = @"SELECT WorkflowActivityStepSpecificFormItemId,FormConfigCode,FormItemCode,FormDatabase,FormTable,BoundField,ItemTitle,ItemValue,ItemType,
                                            ItemWidth,IsFormTitle,WorkflowActivityStepFormConfigId,CreateAdminId,CreateAdminName,CreateTime,EditAdminId,EditAdminName,UpdateTime,
                                            SubmitRole,FormConfigRows,FormItemRows,WorkflowActivityId,TemplateCode,TemplateName,StepCode,WorkflowCode,WorkflowName,FormConfigTitle,
                                            FormGroupName,ItemShow,IsExecution
                                        FROM oa_workflowactivitystepspecificformitem";
        public WorkflowActivityStepSpecificFormItemData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查工作流活动特殊表单项是否存在
        public async Task<bool> Exists(long workflowActivityStepSpecificFormItemId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowActivityStepSpecificFormItemId=?WorkflowActivityStepSpecificFormItemId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityStepSpecificFormItemId", workflowActivityStepSpecificFormItemId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加工作流活动特殊表单项
        public async Task<WorkflowActivityStepSpecificFormItemEntity> Add(WorkflowActivityStepSpecificFormItemEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("oa_workflowactivitystepspecificformitem", new string[] { "FormConfigCode", "FormItemCode", "ItemTitle", "ItemValue","ItemShow", "ItemType",
                "ItemWidth", "IsFormTitle", "WorkflowActivityStepFormConfigId", "CreateAdminId", "CreateAdminName", "SubmitRole", "WorkflowActivityId", "TemplateCode", "TemplateName",
                "StepCode", "WorkflowCode", "WorkflowName", "FormConfigTitle" ,"FormDatabase","FormTable","BoundField","FormGroupName","FormConfigRows","FormItemRows" });
            sql = string.Format("{0} {1} WHERE WorkflowActivityStepSpecificFormItemId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?FormConfigCode", entity.FormConfigCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormItemCode", entity.FormItemCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?ItemTitle", entity.ItemTitle?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ItemValue", entity.ItemValue?.Trim().ToString(), DbType.String);
            parameters.Add("?ItemShow", entity.ItemShow?.Trim(), DbType.AnsiString);
            parameters.Add("?ItemType", entity.ItemType?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ItemWidth", entity.ItemWidth, DbType.Decimal, size: 6);
            parameters.Add("?IsFormTitle", entity.IsFormTitle, DbType.Boolean);
            parameters.Add("?WorkflowActivityStepFormConfigId", entity.WorkflowActivityStepFormConfigId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?SubmitRole", entity.SubmitRole?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WorkflowActivityId", entity.WorkflowActivityId, DbType.Int64, size: 20);
            parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?StepCode", entity.StepCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormConfigTitle", entity.FormConfigTitle?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormDatabase", entity.FormDatabase?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormTable", entity.FormTable?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?BoundField", entity.BoundField?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormGroupName", entity.FormGroupName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?FormConfigRows", entity.FormConfigRows, DbType.Int32);
            parameters.Add("?FormItemRows", entity.FormItemRows, DbType.Int32);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityStepSpecificFormItemEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改工作流活动特殊表单项
        public async Task<WorkflowActivityStepSpecificFormItemEntity> Update(WorkflowActivityStepSpecificFormItemEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("oa_workflowactivitystepspecificformitem", new string[] { "FormConfigCode", "FormItemCode", "FormDatabase", "FormTable", "BoundField",
                "ItemTitle", "ItemValue","ItemShow", "ItemType", "ItemWidth", "IsFormTitle", "WorkflowActivityStepFormConfigId", "CreateAdminId", "CreateAdminName", "EditAdminId",
                "EditAdminName", "UpdateTime", "SubmitRole", "FormConfigRows", "FormItemRows", "WorkflowActivityId", "TemplateCode", "TemplateName", "StepCode", "WorkflowCode",
                "WorkflowName", "FormConfigTitle","FormGroupName"}, new string[] { "WorkflowActivityStepSpecificFormItemId" });
            sql = string.Format("{0} {1} WHERE WorkflowActivityStepSpecificFormItemId=?WorkflowActivityStepSpecificFormItemId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityStepSpecificFormItemId", entity.WorkflowActivityStepSpecificFormItemId, DbType.Int64, size: 20);
            parameters.Add("?FormConfigCode", entity.FormConfigCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormItemCode", entity.FormItemCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormDatabase", entity.FormDatabase?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormTable", entity.FormTable?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?BoundField", entity.BoundField?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?ItemTitle", entity.ItemTitle?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ItemValue", entity.ItemValue?.Trim(), DbType.String);
            parameters.Add("?ItemShow", entity.ItemShow?.Trim(), DbType.AnsiString);
            parameters.Add("?ItemType", entity.ItemType?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ItemWidth", entity.ItemWidth, DbType.Decimal, size: 6);
            parameters.Add("?IsFormTitle", entity.IsFormTitle, DbType.Boolean);
            parameters.Add("?WorkflowActivityStepFormConfigId", entity.WorkflowActivityStepFormConfigId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?UpdateTime", entity.UpdateTime, DbType.DateTime);
            parameters.Add("?SubmitRole", entity.SubmitRole?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?FormConfigRows", entity.FormConfigRows, DbType.Int32, size: 11);
            parameters.Add("?FormItemRows", entity.FormItemRows, DbType.Int32, size: 11);
            parameters.Add("?WorkflowActivityId", entity.WorkflowActivityId, DbType.Int64, size: 20);
            parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?StepCode", entity.StepCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormConfigTitle", entity.FormConfigTitle?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?FormGroupName", entity.FormGroupName?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityStepSpecificFormItemEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除工作流活动特殊表单项
        public async Task<bool> Delete(long workflowActivityStepSpecificFormItemId)
        {
            string sql = @"DELETE FROM oa_workflowactivitystepspecificformitem WHERE WorkflowActivityStepSpecificFormItemId=?WorkflowActivityStepSpecificFormItemId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityStepSpecificFormItemId", workflowActivityStepSpecificFormItemId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取工作流活动特殊表单项
        public async Task<WorkflowActivityStepSpecificFormItemEntity> GetEntity(long workflowActivityStepSpecificFormItemId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowActivityStepSpecificFormItemId=?WorkflowActivityStepSpecificFormItemId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityStepSpecificFormItemId", workflowActivityStepSpecificFormItemId, DbType.Int64);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityStepSpecificFormItemEntity>(sql, parameters);
        }
        #endregion

        #region 获取工作流活动特殊表单项列表
        public async Task<IEnumerable<WorkflowActivityStepSpecificFormItemEntity>> GetList(long workflowActivityId)
        {
            string sql = string.Format("{0} WHERE WorkflowActivityId=?WorkflowActivityId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", workflowActivityId, DbType.Int64, size: 20);
            return await this.databaseContext.Slave.QueryAsync<WorkflowActivityStepSpecificFormItemEntity>(sql, parameters);
        }
        #endregion

        #region 获取工作流活动特殊表单项分页
        public async Task<(IEnumerable<WorkflowActivityStepSpecificFormItemEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM oa_workflowactivitystepspecificformitem {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<WorkflowActivityStepSpecificFormItemEntity, int>(sql, parameters);
        }
        #endregion

        #region 特殊表单数据写入对应表
        public async Task<long> InsertSpecificFormTable(string tableName, Dictionary<string, string> keyValuePairs)
        {
            string sql = SqlCommands.GetInsertSql(tableName, keyValuePairs.Keys.ToArray());
            DynamicParameters parameters = new DynamicParameters();
            foreach (var item in keyValuePairs)
            {
                parameters.Add(item.Key, item.Value);
            }
            sql = string.Format("{0} Select LAST_INSERT_ID()", sql);
            return await databaseContext.Master.ExecuteScalarAsync<long>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 更新特殊表单数据处理已执行
        public async Task<int> UpdateSpecificFormIsExecution(long workflowActivityId, string tableName, int? formConfigRows, int? formItemRows)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", workflowActivityId, DbType.Int64);
            parameters.Add("?FormTable", tableName, DbType.AnsiString);
            string sql = @"UPDATE OA_WorkflowActivityStepSpecificFormItem 
                SET IsExecution = 1 
                WHERE WorkflowActivityId = ?WorkflowActivityId AND FormTable = ?FormTable AND IsExecution = 0";
            if (formConfigRows.HasValue)
            {
                sql = $"{sql} AND FormConfigRows = ?FormConfigRows";
                parameters.Add("?FormConfigRows", formConfigRows, DbType.Int32);
            }
            if (formItemRows.HasValue)
            {
                sql = $"{sql} AND FormItemRows = ?FormItemRows";
                parameters.Add("?FormItemRows", formItemRows, DbType.Int32);
            }
            return await databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 特殊表单数据更新对应表
        public async Task<int> UpdateSpecificFormTable(string tableName, Dictionary<string, string> keyValuePairs, Dictionary<string, string> updateKeyValuePairs)
        {
            string sql = SqlCommands.GetUpdateSql(tableName, keyValuePairs.Keys.ToArray(), updateKeyValuePairs.Keys.ToArray());
            DynamicParameters parameters = new DynamicParameters();
            foreach (var item in keyValuePairs)
            {
                parameters.Add(item.Key, item.Value);
            }
            foreach (var item in updateKeyValuePairs)
            {
                parameters.Add(item.Key, item.Value);
            }
            return await databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction);
        }
        #endregion
    }
}
